package cn.book.bus.utils;

import java.util.concurrent.*;

public class TaskQueueExample {
    // 创建一个并发安全的任务队列
    private static final ConcurrentLinkedQueue<String> taskQueue = new ConcurrentLinkedQueue<>();

    public static void main(String[] args) {


        // 定义线程池核心参数
        int corePoolSize = 5; // 核心线程数
        int maximumPoolSize = 10; // 最大线程数
        long keepAliveTime = 60L; // 空闲线程存活时间（单位：秒）
        TimeUnit unit = TimeUnit.SECONDS; // 时间单位

        // 使用阻塞队列作为工作队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();

        // 创建线程工厂，默认即可
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        // 创建拒绝策略，这里使用CallerRunsPolicy，当队列满且线程达到最大时，主线程直接运行被拒绝的任务
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        // 创建线程池实例
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);


        // 提交任务到线程池
        for (int i = 0; i < 2000000; i++) {
            final int taskId = i;
            Runnable task = () -> {

                System.out.println("Task " + taskId + " is being executed by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(50000); // 模拟耗时操作
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            };
            executor.execute(task);
        }
        // 关闭线程池
        // shutdown()方法不会立即停止正在执行的任务，而是不再接受新的任务，并等待所有已提交任务执行完毕
        executor.shutdown();

        // 等待所有任务完成（可选，取决于你的应用需求）
        try {
            if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                System.err.println("Some tasks were not terminated within the specified time.");
            }
        } catch (InterruptedException ie) {
            // 处理中断异常
            executor.shutdownNow(); // 中断未完成的任务
            Thread.currentThread().interrupt();
        }
    }
}

